package com.ipay.service.impl;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.ipay.common.Base64Coder;
import com.ipay.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.ipay.core.HttpGateway;
import com.ipay.core.Param;
import com.ipay.service.ApiPayService;
import com.ipay.utils.IPUtils;
import com.ipay.utils.MD5;
import com.ipay.utils.MapUtils;



@Service("apiPayService")
public class ApiPayServiceImpl implements ApiPayService {
    private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpGateway gateway;
	
	@Override
	public Map<String, Object> wxJsPay(Map<String,String> map,String mchPayKey) {
		Map<String, Object> wxPayMap=new HashMap<String,Object>();
		wxPayMap.put("code", 500);
		System.out.println("wxJsPay====:"+JSON.toJSONString(map));
		String strtosign = MapUtils.formatUrlMap(map, false, false);
		gateway.url = "https://pay.swiftpass.cn/pay/gateway";
		//TODO 查询商户相关数据
		String signstr = MD5.sign(strtosign, "&key=" + mchPayKey, "utf-8");
		map.put("sign", signstr);
		Param param = Param.create();
		param.putAll(map);
		logger.info("============:"+JSON.toJSONString(param));
		// 银行预支付接口
		Param resultparam = gateway.post(param);
		logger.info("============:resultparam----->" + resultparam);
		String status = resultparam.get("status");
		
		if (status.equals("0")) {// 成功
			String result_code = resultparam.get("result_code");// 业务成功结果
			if (result_code.equals("0")) {
				wxPayMap.put("code", 0);
				wxPayMap.put("pay_info", resultparam.get("pay_info"));
				wxPayMap.put("token_id", StringUtil.isNotEmptyValue(resultparam.get("token_id"), ""));
				wxPayMap.put("pay_url", StringUtil.isNotEmptyValue(resultparam.get("pay_url"), ""));
			}else{
				wxPayMap.put("msg", resultparam.get("message"));
			}
		}else{
			wxPayMap.put("msg", resultparam.get("message"));
		}
		return wxPayMap;
	}


	/**
	 *第三方回调处理
	 * @param map ////参数
	 * @param mchPayKey //秘钥
	 * @param gatewayUrl //回调url
	 */
	@Override
	public void dsfNotifyUrl(Map<String,String> map,String mchPayKey,String gatewayUrl) {
		/*mapdsfbak.put("status",order.getStatus());//1已支付
		mapdsfbak.put("sponsorOrderNo",order.getSponsorOrderNo());//发起方订单号
		mapdsfbak.put("resource",order.getResource());//来源（0 微信、1 支付宝）
		mapdsfbak.put("amount", String.valueOf(total_fee));//金额
		mapdsfbak.put("recordNo", order.getRecordno());//商户订单号
		mapdsfbak.put("time_end", order.getTimeEnd());//
		mapdsfbak.put("bank_type", order.getBankType());//
		mapdsfbak.put("openid", order.getOpenid());//*/
		try{
			System.out.println("wxJsPay====:"+JSON.toJSONString(map));
			String strtosign = MapUtils.formatUrlMap(map, false, false);
			gateway.url = gatewayUrl;
			//TODO 查询商户相关数据
			String parameter= Base64Coder.encode(strtosign);
			String signstr = MD5.sign(parameter, "&payKey=" + mchPayKey, "utf-8");
			map.put("sign", signstr);
			Param param = Param.create();
			param.putAll(map);
			logger.info("============:"+JSON.toJSONString(param));
			// 银行预支付接口
			Param resultparam = gateway.post(param);
			logger.info("============:resultparam----->" + resultparam);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	@Override
	public String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		StringBuffer result=new StringBuffer();
		try {

			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！"+e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return result.toString();
	}


}
